<template>
  <div>
    <el-dialog
      :title="info.isAdd ? '商品添加' : '商品编辑'"
      :visible.sync="info.isshow"
      @closed="closed"
      @opened="opened"
    >
      {{ user }}
      <el-form :model="user">
        <el-form-item label="一级分类" label-width="120px">
          <el-select
            v-model="user.first_cateid"
            placeholder="请选择一级分类"
            @change="changeFirst"
          >
            <!-- 一级分类 -->
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" label-width="120px">
          <el-select v-model="user.second_cateid" placeholder="请选择二级分类">
            <!-- 二级分类 -->
            <el-option
              v-for="item in secondCateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="user.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="user.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="user.market_price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="120px">
          <div class="upload">
            <p>+</p>
            <input type="file" @change="changeImg" v-if="info.isshow" />
            <img :src="imgUrl" alt="" v-if="imgUrl" />
          </div>
        </el-form-item>
        <el-form-item label="商品规格" label-width="120px">
          <el-select
            v-model="user.specsid"
            placeholder="请选择商品规格"
            @change="changeSpecs"
          >
            <!-- 遍历规格 -->
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" label-width="120px">
          <el-select
            v-model="user.specsattr"
            placeholder="请选择规格属性"
            multiple
          >
            <!-- 属性列表 -->
            <el-option
              v-for="item in attrsList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="user.isnew" :label="1">是</el-radio>
          <el-radio v-model="user.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" label-width="120px">
          <el-radio v-model="user.ishot" :label="1">是</el-radio>
          <el-radio v-model="user.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="user.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="商品描述" label-width="120px">
          <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="add" v-if="this.info.isAdd"
          >添 加</el-button
        >
        <el-button type="primary" @click="update" v-else>修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import E from "wangeditor";
import { mapGetters, mapActions } from "vuex";
import { goodsadd, goodsinfo, goodsedit, catelist } from "../../../http/api";

import { errorAlert, successAlert } from "../../../utils/alert";
import path from "path";
export default {
  props: ["info"],
  data() {
    return {
      user: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: "",
        ishot: "",
        status: 1,
      },
      imgUrl: "",
      secondCateList: [],
      attrsList: [],
    };
  },
  computed: {
    ...mapGetters({
      cateList: "cate/list",
      specsList: "specs/list",
    }),
  },
  methods: {
    ...mapActions({
      reqCateList: "cate/reqList",
      reqSpecsList: "specs/reqList",
      reqList: "goods/reqList",
      reqListTwo: "goods/reqListTwo",
    }),
    async changeFirst() {
      this.user.second_cateid = "";
      let res = await catelist({ pid: this.user.first_cateid });
      if (res.data.code == 200) {
        this.secondCateList = res.data.list ? res.data.list : [];
      }
    },
    changeSpecs() {
      this.user.specsattr = [];
      let obj = this.specsList.find((item) => item.id == this.user.specsid);
      this.attrsList = obj ? obj.attrs : [];
    },
    //添加
    add() {
      let data = {
        ...this.user,
        specsattr: JSON.stringify(this.user.specsattr),
        description: this.editor.txt.html(),
      };
      goodsadd(data).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);
          this.empty();
          this.info.isshow = false;
          this.reqListTwo();
        }
      });
    },
    changeImg(e) {
      let file = e.target.files[0];

      //判断文件类型
      let imgArr = [".jpg", ".jpeg", ".png", ".gif"];
      //原生js获取后缀名
      // let extname=file.name.slice(file.name.lastIndexOf("."))
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的文件格式");
        return;
      }

      //根据文件生成一个图片地址,仅显示给用户看
      this.imgUrl = URL.createObjectURL(file);
      //赋值给user
      this.user.img = file;
    },
    //取消
    cancel() {
      this.info.isshow = false;
    },
    //清空
    empty() {
      this.user = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: "",
        ishot: "",
        status: 1,
      };
      this.imgUrl = "";
      this.secondCateList = [];
      this.attrsList = [];
    },

    //获取一个数据
    async getOne(id) {
      let res = await goodsinfo({ id });
      this.user = res.data.list;
      this.imgUrl = this.$pre + res.data.list.img;
      //补id字段,发送修改时需要使用
      this.user.id = id;
      let res1 = await catelist({ pid: this.user.first_cateid });
      if (res1.data.code == 200) {
        this.secondCateList = res1.data.list ? res1.data.list : [];
      }
      this.user.specsattr = JSON.parse(this.user.specsattr);
      if (this.editor) {
        this.editor.txt.html(this.user.description);
      }
    },
    update() {
      let data = {
        ...this.user,
        specsattr:JSON.stringify(this.user.specsattr),
        description: this.editor.txt.html(),
      }
      goodsedit(data).then((res) => {
        if ((res.data.code = 200)) {
          successAlert(res.data.msg);
          this.info.isshow = false;
          this.empty();
          //通知父组件刷新表格
          this.reqListTwo();
        }
      });
    },
    //如果是编辑窗口取消，清空数据，添加窗口的取消，不需要清空
    closed() {
      //如果是添加取消,将编辑器内容存在user.description中
      if (this.info.isAdd) {
        this.user.description = this.editor.txt.html();
      }

      if (!this.info.isAdd) {
        this.empty();
      }
    },
    //弹框出现
    opened() {
      //创建富文本编辑器
      this.editor = new E("#editor");
      this.editor.create();
      this.editor.txt.html(this.user.description);
    },
  },
  mounted() {
    this.reqCateList();
    this.reqSpecsList(true);
  },
};
</script>

<style lang="less" scoped>
@import "../../../less/index.less";
.upload {
  position: relative;
  width: 150px;
  height: 150px;
  border: 1px dashed #333;
}
.upload p {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 150px;
}
.upload input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 100;
  cursor: pointer;
}
.upload img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>